﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using System.Text.RegularExpressions;

namespace Domain
{
    [HasSelfValidation]
    public class Empresa : Operador
    {
        public long? Logo { get; set; }

        [StringLengthValidator(5, 50, MessageTemplate = "Debe ingresar una Razón Social entre 5 y 50 caracteres")]
        public string RazonSocial { get; set; }

        [StringLengthValidator(5, 50, MessageTemplate = "Debe especificar una Rubro")]
        public string Rubro { get; set; }

        public double? Lat { get; set; } 
        public double? Long {get; set;} 

        public List<Publicacion> Publicaciones { get; set; }

        public Empresa() { }
        public Empresa(long _UserName, string _Password, string _EMail,
                       long? _Logo, string _RazonSocial,  
                       string _Rubro, List<Publicacion> _Publicaciones, double? _Lat, double? _Long):
                       base (_UserName, _Password, _EMail)
        {
            this.UserName = _UserName;
            this.Logo = _Logo;
            this.RazonSocial = _RazonSocial;
            this.Rubro = _Rubro;
            this.Publicaciones = _Publicaciones;
            this.Lat = _Lat;
            this.Long = _Long;

        }

        [SelfValidation]
        public void Check_CUIT(ValidationResults results)
        {
            string errores = EmpresaUtils.ValidarCUIL(this.UserName.ToString());

            if(!string.IsNullOrEmpty(errores))
            {
                results.AddResult(new ValidationResult(errores, this, "", "", null));
            }
        }

        [SelfValidation]
        public void Check_LatLong(ValidationResults results)
        {
            if((this.Lat.HasValue && 
               !this.Long.HasValue)||
               (!this.Lat.HasValue && 
               this.Long.HasValue))
                results.AddResult(new ValidationResult("Se debe ingresar latitud y longitud o ninguno", this, "", "", null));

        }
    }

    public static class EmpresaUtils
    {
        public static string ValidarCUIL(string cuil)
        {
            cuil = cuil.Replace("-", "");
            string error = string.Empty;

            if (cuil.Length < 11)
            {
                error = "El CUIL/T ingresado está incompleto.";
            }
            else if (!esNumerico(cuil))
            {
                error = "El CUIL/T ingresado no es válido.";
            }
            else if (!CUIL_Valido(cuil))
            {
                error = "El CUIL/T ingresado no es válido.";
            }

            return error;
        }

        public static bool CUIL_Valido(string CUIL)
        {

            string patron = @"^\d{11}$";
            Regex re = new Regex(patron);

            bool resp = re.IsMatch(CUIL);

            if (resp)
            {

                string FACTORES = "54327654321";
                double dblSuma = 0;

                if (!(CUIL.Substring(0, 1).ToString() != "3" && CUIL.Substring(0, 1).ToString() != "2"))
                {
                    for (int i = 0; i < 11; i++)
                        dblSuma = dblSuma + int.Parse(CUIL.Substring(i, 1).ToString()) * int.Parse(FACTORES.Substring(i, 1).ToString());

                    resp = Math.IEEERemainder(dblSuma, 11) == 0;
                }
                else
                {
                    resp = false;
                }
            }


            return resp;

        }

        public static bool esNumerico(string Valor)
        {
            bool ValidoDatos = false;

            Regex numeros = new Regex(@"^\d{1,}$");

            if (Valor.Length != 0)
            {
                ValidoDatos = numeros.IsMatch(Valor);
            }
            return ValidoDatos;
        }
    }
}
